package com._4pd.demo.formal.template;

import com._4pd.demo.formal.crd.AiOperator;
import com._4pd.demo.formal.crd.AiOperatorSpec;
import com._4pd.demo.formal.crd.Algorithm;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;
import io.fabric8.kubernetes.api.model.GenericKubernetesResource;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FreeMakerRender implements AiTemplateRender{
    private final Configuration cfg;

    public FreeMakerRender() throws IOException {
        cfg = new Configuration(new Version("2.3.23"));
        cfg.setDirectoryForTemplateLoading(new File("src/main/resources/freemarker/"));
        cfg.setDefaultEncoding("UTF-8");
    }

    @Override
    public String render(AiOperator resource) throws Exception {
        AiOperatorSpec aiOperatorSpec = resource.getSpec();
//        String spec_json_str = JSONObject.toJSONString(resource.get("spec"));
//        AiOperatorSpec aiOperatorSpec = JSONObject.parseObject(spec_json_str, AiOperatorSpec.class);
        // 读取根数据
        Map<String,Object> root = new HashMap<>();
        root.put("Kind",resource.getKind());
        root.put("ApiVersion",resource.getApiVersion());
        root.put("Metadata",resource.getMetadata());
        root.put("name","operator-"+resource.getMetadata().getName()+"");
        // 构造free marker数据
        Map<String, Object> data = new HashMap<>();
        data.put("root", root);
        data.put("run_params", aiOperatorSpec);

        // 获取模版
        Algorithm algorithm = aiOperatorSpec.getAlgorithm();
        Template template = cfg.getTemplate(algorithm.getType()+".yaml");
        // 渲染Yaml
        StringWriter out = new StringWriter();
        template.process(data, out);
        out.flush();
        return out.getBuffer().toString();
    }
}
